package softwaretest.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import softwaretest.util.JwtUtil;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class JwtRequestFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(JwtRequestFilter.class);

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        // 获取请求路径
        String path = request.getRequestURI();

        // 排除注册和登录接口
        if (path.equals("/api/users/register") || path.equals("/api/users/login")) {
            logger.info("Bypassing JWT validation for path: {}", path);
            chain.doFilter(request, response); // 直接放行
            return;
        }

        // 其他接口需要验证 Token
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 去掉 "Bearer " 前缀
        }

        if (token == null) {
            logger.warn("Token not found in request");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Token not found");
            return;
        }

        if (!jwtUtil.validateToken(token)) {
            logger.warn("Invalid token: {}", token);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Invalid token");
            return;
        }

        logger.info("Token validated successfully for request: {}", request.getRequestURI());
        chain.doFilter(request, response);
    }
}